package com.act262.vote;

import java.io.IOException;
import java.util.List;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import com.act262.vote.bean.Rule;
import com.act262.vote.utils.VoteCore;

public class Vote {

	public interface CallBack {
		/**
		 * 更新显示的内容
		 * 
		 * @param textArea
		 */
		public void updateResult(String result);
	}

	CloseableHttpClient mHttpClient = null;

	CallBack mCallBack = null;

	// 间隔时间,默认1s
	int mTime = 1000;

	/** 执行状态 */
	int status = 0x0;
	public static final int STATUS_STOP = 0x00;
	public static final int STATUS_RUNNING = 0x01;
	public static final int STATUS_PAUSE = 0x02;

	public Vote(CallBack callBack) {
		if (!(callBack instanceof CallBack)) {
			throw new ClassCastException("没有实现该回调接口");
		}
		mCallBack = callBack;
	}

	/**
	 * 开始运行,
	 * 
	 * @param ruleList
	 *            参数列表
	 */
	public void start(List<Rule> ruleList) {
		status = STATUS_RUNNING;
		mHttpClient = HttpClientBuilder.create().build();
		vote(ruleList);
	}

	/**
	 * 停止运行
	 */
	public void stop() {
		status = STATUS_STOP;
		finish();
	}

	/**
	 * 暂停运行
	 */
	public void pause() {
		status = STATUS_PAUSE;
	}

	/**
	 * 继续运行
	 */
	public void continueRun() {

		// 正在暂停中。。。
		if (status == STATUS_PAUSE) {
			status = STATUS_RUNNING;
			System.out.println("pause-->running");
		} // 已经运行或者已经关闭了
		else if (status == STATUS_RUNNING || status == STATUS_STOP) {

		}
	}

	/**
	 * 设置执行的间隔时间,默认为1秒
	 * 
	 * @param time
	 */
	public void setTime(int time) {
		this.mTime = time * 1000;
	}

	public boolean isStop() {
		return status == STATUS_STOP;
	}

	public boolean isPause() {
		return status == STATUS_PAUSE;
	}

	public boolean isRunning() {
		return status == STATUS_RUNNING;
	}

	private void vote(List<Rule> ruleList) {

		for (int i = 0, count = ruleList.size(); i < count; i++) {

			try {
				// 设定执行的间隔时间
				Thread.sleep(mTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			// 暂停中。。。
			while (status == STATUS_PAUSE) {
				System.out.println("pause...");
			}

			if (status == STATUS_STOP) {
				return;
			} else if (status == STATUS_RUNNING) {
				doVote(ruleList.get(i), i);
			}
		}
	}

	private void doVote(Rule rule, int i) {
		Thread thread = new Thread(new VoteThread(rule), "" + i);
		thread.start();
	}

	private void finish() {
		try {
			mHttpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private final class VoteThread implements Runnable {

		Rule rule;

		public VoteThread(Rule rule) {
			this.rule = rule;
		}

		@Override
		public void run() {
			System.out.println("当前运行的线程    :  " + Thread.currentThread());
			mCallBack.updateResult(VoteCore.vote(mHttpClient, this.rule));
		}

	}
}
